<template>
  <div>
    <el-input :model-value="formulaStr" :readonly="true" :placeholder="placeh">
      <template #append>
        <BaseButton :icon="toolsIcon" @click="openFormula" />
      </template>
    </el-input>
    <Dialog :title="title" v-model="visible" width="1100px" :before-close="save">
      <el-row :gutter="8" style="margin-bottom: 10px">
        <el-col :span="18" style="font-weight: 700"> 条件公式：{{ formulaStr }} </el-col>
        <el-col :span="6">
          <el-button type="success" style="float: right" @click="addRow">添加</el-button>
        </el-col>
      </el-row>
      <Table
        key="flomulaSet"
        :data="formulaList"
        :columns="formulaCols"
        row-class-name="rowItem"
        :show-action="false"
      >
        <template #column="e">
          <formColChiose
            v-model="e.row.ColId"
            :form-id="[formId]"
            :source="e.row"
            labelField="Label"
            @change="
              (val, form) => {
                if (form != null) {
                  e.row.DataType = form.col.DataType
                } else {
                  e.row.DataType = null
                }
                refreshFormula()
              }
            "
          />
        </template>
        <template #condition="e">
          <el-select v-model="e.row.Con" placeholder="链接符号" @change="refreshFormula">
            <el-option v-if="e.row.DataType !== 3" label="=" :value="0" />
            <el-option v-if="e.row.DataType !== 3" label="!=" :value="1" />
            <el-option
              v-if="e.row.DataType !== 4 && e.row.DataType !== 3 && e.row.DataType !== 0"
              label=">"
              :value="2"
            />
            <el-option
              v-if="e.row.DataType !== 4 && e.row.DataType !== 3 && e.row.DataType !== 0"
              label="<"
              :value="3"
            />
            <el-option
              v-if="e.row.DataType !== 4 && e.row.DataType !== 3 && e.row.DataType !== 0"
              label=">="
              :value="4"
            />
            <el-option
              v-if="e.row.DataType !== 4 && e.row.DataType !== 3 && e.row.DataType !== 0"
              label="<="
              :value="5"
            />
            <el-option v-if="e.row.DataType !== 4" label="in" :value="6" />
            <el-option v-if="e.row.DataType !== 4" label="not in" :value="7" />
          </el-select>
        </template>
        <template #value="e">
          <el-input-number
            v-if="e.row.DataType == 1 || e.row.DataType == 5"
            v-model="e.row.Value"
            style="width: 100%"
            :precision="e.row.DataType == 5 ? 0 : null"
            placeholder="值"
            @change="refreshFormula"
          />
          <el-switch
            v-else-if="e.row.DataType == 4"
            v-model="e.row.Value"
            @change="refreshFormula"
          />
          <el-date-picker
            v-else-if="e.row.DataType == 7"
            v-model="e.row.Value"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="值"
            @change="refreshFormula"
          />
          <el-date-picker
            v-else-if="e.row.DataType == 6"
            v-model="e.row.Value"
            type="datetime"
            format="yyyy-MM-dd HH:mm"
            value-format="yyyy-MM-dd HH:mm"
            placeholder="值"
            @change="refreshFormula"
          />
          <el-time-picker
            v-else-if="e.row.DataType == 2"
            v-model="e.row.Value"
            format="HH:mm"
            value-format="HH:mm"
            placeholder="值"
            @change="refreshFormula"
          />
          <el-input
            v-else
            v-model="e.row.Value"
            :placeholder="e.row.Con == 6 ? '多个小写 , 分隔' : '值'"
            @change="refreshFormula"
          />
        </template>
        <template #keywords="e">
          <el-input
            v-model="e.row.Keywords"
            placeholder="配合字段使用的筛选方案"
            :clearable="true"
          />
        </template>
        <template #sort="e">
          <BaseButton
            v-if="e.row.index != maxIndex"
            size="small"
            :icon="downIcon"
            :circle="true"
            @click="setSort(e.row, true)"
          />
          <BaseButton
            v-if="e.row.index != minIndex"
            size="small"
            :icon="upIcon"
            :circle="true"
            @click="setSort(e.row, false)"
          />
        </template>
        <template #action="e">
          <BaseButton
            size="small"
            :icon="dropIcon"
            type="danger"
            :circle="true"
            @click="dropItem(e.row)"
          />
        </template>
        <template #isAnd="e">
          <el-switch
            v-model="e.row.IsAnd"
            :disabled="index == 1"
            active-text="And"
            inactive-text="Or"
            @change="refreshFormula"
          />
        </template>
      </Table>
    </Dialog>
  </div>
</template>

<script>
import { conditionDic } from '@/flow/config/flowConfig'
import { useIcon } from '@/hooks/web/useIcon'
import { Dialog } from '@/components/Dialog'
import { Table } from '@/components/Table'
import { formColChiose } from '@/customForm/components/form'
export default {
  components: {
    Dialog,
    Table,
    formColChiose
  },
  props: {
    modelValue: {
      type: Object,
      default: () => {
        return {
          NodeId: null,
          FormId: null,
          Items: null,
          Formula: null
        }
      }
    },
    nodeName: {
      type: String,
      default: null
    },
    readonly: {
      type: Boolean,
      default: false
    },
    nodeId: {
      type: String,
      default: null
    },
    defFormId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      title: null,
      toolsIcon: useIcon({ icon: 'ep:tools' }),
      upIcon: useIcon({ icon: 'ep:up' }),
      downIcon: useIcon({ icon: 'ep:down' }),
      editIcon: useIcon({ icon: 'ep:edit' }),
      dropIcon: useIcon({ icon: 'ep:delete' }),
      placeh: null,
      index: 0,
      formId: null,
      minIndex: 0,
      maxIndex: 0,
      curFormId: [],
      formulaList: [],
      formulaStr: null,
      visible: false,
      formulaCols: [
        {
          field: 'column',
          label: '条件字段',
          align: 'center',
          minWidth: 300,
          slotName: 'column'
        },
        {
          field: 'Keywords',
          label: '筛选方案名',
          align: 'left',
          minWidth: 120,
          slotName: 'keywords'
        },
        {
          field: 'condition',
          label: '链接符号',
          align: 'center',
          minWidth: 100,
          slotName: 'condition'
        },
        {
          field: 'value',
          label: '值',
          align: 'center',
          minWidth: 150,
          slotName: 'value'
        },
        {
          field: 'isAnd',
          label: '链接条件',
          align: 'center',
          minWidth: 100,
          slotName: 'isAnd'
        },
        {
          field: 'sort',
          label: '排序',
          align: 'center',
          width: 120,
          slotName: 'sort'
        },
        {
          field: 'action',
          label: '操作',
          align: 'center',
          width: 60,
          slotName: 'action'
        }
      ]
    }
  },
  computed: {},
  watch: {
    modelValue: {
      handler(val) {
        if (val) {
          this.formula = val
          this.formulaStr = val.Formula
        } else {
          this.formula = null
          this.formulaStr = null
        }
      },
      immediate: true
    },
    nodeName: {
      handler(val) {
        if (val) {
          this.placeh = val + '节点入方向条件公式'
        } else {
          this.placeh = '节点入方向条件公式'
        }
      },
      immediate: true
    }
  },
  mounted() {},
  methods: {
    openFormula() {
      this.visible = true
      this.$nextTick(this.reset)
    },
    dropItem(row) {
      const index = this.formulaList.findIndex((c) => c.index === row.index)
      if (index !== -1) {
        this.formulaList.splice(index, 1)
        this.refreshFormula()
        if (this.formulaList.length === 0) {
          this.minIndex = 0
          this.maxIndex = 0
        } else {
          this.minIndex = this.formulaList[0].index
          this.maxIndex = this.formulaList[this.formulaList.length - 1].index
        }
      }
    },
    addRow() {
      this.formulaList.push({
        index: this.index,
        IsAnd: true,
        Con: 0,
        DataType: null,
        ColId: null,
        Label: null,
        Value: null,
        Keywords: null
      })
      this.maxIndex = this.index
      this.index = this.index + 1
    },
    setSort(row, isDown) {
      const index = this.formulaList.findIndex((c) => c.index === row.index)
      if (isDown) {
        const to = this.formulaList[index + 1]
        const t = to.index
        to.index = row.index
        row.index = t
        this.formulaList[index + 1] = row
        this.formulaList[index] = to
      } else {
        const to = this.formulaList[index - 1]
        const t = to.index
        to.index = row.index
        row.index = t
        this.formulaList[index - 1] = row
        this.formulaList[index] = to
      }
    },
    refreshFormula() {
      if (this.formulaList.length === 0) {
        this.formulaStr = null
        return
      }
      const list = this.formulaList.filter((a) => a.ColId !== null && a.Value !== null)
      if (list.length > 0) {
        let old = list[0]
        let str = old.Label + ' ' + conditionDic[old.Con].text + ' ' + old.Value
        if (list.length > 1) {
          if (old.IsAnd === false) {
            str = '(' + str + ' or '
          } else {
            str = str + ' and '
          }
          const end = list.length - 1
          for (let i = 1; i < list.length; i++) {
            const t = list[i]
            if (t.IsAnd === false && old.IsAnd && i !== end) {
              str = str + '('
            }
            str = str + t.Label + ' ' + conditionDic[t.Con].text + ' ' + t.Value
            if (t.IsAnd && old.IsAnd === false) {
              str = str + ')'
            }
            if (i !== end) {
              str = str + (t.IsAnd ? ' and ' : ' or ')
            }
            old = t
          }
        }
        // eslint-disable-next-line no-undef
        if (old.IsAnd === false && list[end - 1].IsAnd === false) {
          str = str + ')'
        }
        this.formulaStr = str
      } else {
        this.formulaStr = null
      }
    },
    save() {
      const data = {
        NodeId: this.nodeId,
        FormId: this.formId,
        Formula: this.formulaStr === '' ? null : this.formulaStr,
        Items: null
      }
      if (this.formulaStr != null) {
        const list = this.formulaList.filter((a) => a.ColId !== null && a.Value !== null)
        data.Items = list.map((c) => {
          return {
            ColId: c.ColId,
            Label: c.Label,
            Con: c.Con,
            Keywords: c.Keywords,
            Vals: c.Con === 6 || c.Con === 7 ? c.Value.split(',') : null,
            Val: c.Con !== 6 && c.Con !== 7 ? c.Value : null,
            IsAnd: c.IsAnd
          }
        })
      }
      this.formula = data
      this.visible = false
      this.$emit('update:modelValue', data)
      this.$emit('change', data)
    },
    reset() {
      this.title = this.nodeName + '节点入站条件'
      if (this.formula == null) {
        this.formulaStr = null
        this.formId = this.defFormId
        this.formulaList = []
        this.index = 0
        this.minIndex = 0
        this.maxIndex = 0
      } else {
        this.formulaStr = this.formula.Formula
        this.formId = this.formula.FormId == null ? this.defFormId : this.formula.FormId
        this.index = 0
        if (this.formula.Items != null && this.formula.Items.length > 0) {
          this.formulaList = this.formula.Items.map((c) => {
            const clone = Object.assign({}, c)
            clone.index = this.index
            clone.dataType = null
            clone.Value = c.Con === 6 ? c.Vals.join(',') : c.Val
            this.index = this.index + 1
            return clone
          })
        }
        this.minIndex = 0
        this.maxIndex = this.index - 1
      }
    }
  }
}
</script>
